﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace TestJQGrid
{
    public partial class RejectionRule : System.Web.UI.Page
    {
        #region Global declarations
        
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                fill_fields();
                fill_Funs();
                fill_dlFormula();

                lblWhenExp.Text = "";
                tableNames.Value = "";
                btnSave.Visible = false;
                ViewState["formulaIDToUpdate"] = 0;

                lblMenuName.Text = "REJECTION RULE";
                lblMenuName.Font.Bold = true;
                lblMenuName.Font.Size = 14;
                lblMenuName.ForeColor = System.Drawing.Color.Navy;
            }

         //   btnReset.Attributes.Add("OnClick", "document.forms[0].reset();return false;");
        }

        private void fill_fields()
        {
            listFields.DataSource = GlobalMethods.ExecuteSelectQuery("select (cp.TableName + '.' + cp.ColumnName) AS ColumnsList,('@('+cp.TableName + '.' + cp.ColumnName+')') AS ColumnsListVal  from ColumnProperties cp where cp.TableName in ( select tr.RelatedTable from TableRelation tr, ProductList pl where pl.ProductName = '" + Session["ProductName"].ToString() + "' AND pl.TableName = tr.PrimaryTable ) OR cp.TableName in ( select pl.TableName from ProductList pl where pl.ProductName = '" + Session["ProductName"].ToString() + "') AND cp.ColumnName not in ('EntryStatus','Product','TransId','ProductName') Order By ColumnsList");
            listFields.DataTextField = "ColumnsList";
            listFields.DataValueField = "ColumnsListVal";
            listFields.DataBind();
        }

        private void fill_Funs()
        {
            listFormula.DataSource = GlobalMethods.ExecuteSelectQuery("select FormulaName as ctxt,'$'+FormulaName+'()' as cval from FormulaTable where ProductName='" + Session["ProductName"].ToString() + "' and FormulaType='Formula' and SubType ='Rejection Rule'  order by FormulaName");
            listFormula.DataTextField = "ctxt";
            listFormula.DataValueField = "cval";
            listFormula.DataBind();
        }

        private void fill_dlFormula()
        {
            dlFormula.DataSource = GlobalMethods.ExecuteSelectQuery("select FormulaName,ID from FormulaTable where FormulaType='Rejection' order by FormulaName");
            dlFormula.DataBind();
        }

        protected void btnValidate_Click(object sender, EventArgs e)
        {
            //if (validateForm() == true)
            //{
            string result = "";
            string when_expResult = "", when_expResultType = "";
            string when_expression = txtWhenPart.Text.Trim().Replace(" ", "");

                if (when_expression.Length > 0)
                {
                    object obj = ExpressionEvaluator.isValidExp(when_expression);
                    when_expResult = Convert.ToString(obj);
                    when_expResultType = obj.GetType().ToString();
                }

                if (when_expResult !="" &&  when_expResult.ToUpper() != "TRUE" && when_expResult.ToUpper() != "FALSE") //when_expResult.IndexOf("Invalid") > -1
                {
                    if (string.IsNullOrEmpty(result))
                    {
                        result = " WHEN expression";
                    }
                    else
                    {
                        result += " and WHEN expression";
                    }

                    lblWhenExp.Text = "Invalid expression";
                    lblWhenExp.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    if (when_expResult != "")
                    {
                        lblWhenExp.Text = "Valid expression";
                        lblWhenExp.ForeColor = System.Drawing.Color.Green;
                    }
                }

                if (result != "")
                {
                    btnSave.Visible = false;
                }
                else
                {
                    btnSave.Visible = true;
                }
           // }            
        }

        private bool validateForm()
        {
            string msg = "";

            if (txtFurmulaName.Text.Trim().Replace(" ", "").Length == 0 || txtFurmulaName.Text == string.Empty)
            {
                msg += "Please enter the formula name.";
            }
            
            if (msg != "")
            {
                WebMsgBox.Show(msg);
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// This function save's the formula in the table.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string strWhere = "";
            string expQuery = "";
            
            strWhere = txtWhenPart.Text.Trim().Replace(" ", "").Replace("@", "").Replace("$", "");
            strWhere = strWhere.Replace("SUM", "").Replace("MIN", "").Replace("MAX", "").Replace("AVG", "").Replace("COUNT", "");

            expQuery = "select * ";
            expQuery += " from " + tableNames.Value;
            if (strWhere != "")
                expQuery += " where " + strWhere;
                
            if (Convert.ToInt32(ViewState["formulaIDToUpdate"]) != 0)
            {
                if (GlobalMethods.ExecuteNonQuery("update FormulaTable set FormulaName='" + txtFurmulaName.Text.Trim() + "',WhenPart='" + txtWhenPart.Text.Trim().Replace(" ", "") + "',FinalQuery='" + expQuery.Trim() + "',FromDate='" + Convert.ToDateTime(txtFromDate.Text).ToString("yyyy-MM-dd") + "',ToDate='" + Convert.ToDateTime(txtToDate.Text).ToString("yyyy-MM-dd") + "' where ID=" + Convert.ToInt32(ViewState["formulaIDToUpdate"])) > 0)
                {
                    fill_dlFormula();
                    WebMsgBox.Show("Rejection rule updated successfully.");
                }
            }
            else
            {
                GlobalMethods.ExecuteNonQuery("insert into FormulaTable values('" + txtFurmulaName.Text.Trim().Replace("'", "") + "','" + txtWhenPart.Text.Trim() + "','','','Rejection','" + DateTime.Now.ToString() + "','" + Session["loginId"].ToString() + "','" + expQuery + "','" + Session["ProductName"].ToString() + "','" + Convert.ToDateTime(txtFromDate.Text).ToString() + "','" + Convert.ToDateTime(txtToDate.Text).ToString() + "')");
                fill_dlFormula();
                WebMsgBox.Show("Rejection rule Saved Successfully");
            }
        }

        protected void lbt_formula_Click(object sender, EventArgs e)
        {
            int rid = 0;
            LinkButton lbtn = sender as LinkButton;

            if (lbtn != null)
            {
                rid = Convert.ToInt32(lbtn.CommandArgument);
                showFormulDetails(rid);
                ViewState["formulaIDToUpdate"] = rid;
            }
        }

        private void showFormulDetails(int fid)
        {
            DataTable dt = new DataTable();
            dt = GlobalMethods.ExecuteSelectQuery("select * from FormulaTable ft where ft.ID=" + fid);

            if (dt != null && dt.Rows.Count > 0)
            {
                txtFurmulaName.Text = dt.Rows[0]["FormulaName"].ToString();
                txtWhenPart.Text = dt.Rows[0]["WhenPart"].ToString();

                txtFromDate.Text = Convert.ToDateTime(dt.Rows[0]["FromDate"].ToString()).ToString("dd-MMM-yyyy");
                txtToDate.Text = Convert.ToDateTime(dt.Rows[0]["ToDate"].ToString()).ToString("dd-MMM-yyyy");
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            resetForm();
        }

        private void resetForm()
        {
            txtFurmulaName.Text = "";
            txtWhenPart.Text = "";

            lblWhenExp.Text = "";

            txtFromDate.Text = "";
            txtToDate.Text = "";

            ViewState["formulaIDToUpdate"] = 0;
            btnSave.Visible = false;
        }
    }
}